package com.ltu.biz;


import java.util.Objects;

import org.apache.logging.log4j.core.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ltu.domain.mp_entity.OrderEntity;
import com.ltu.domain.mp_entity.PayRecord;
import com.ltu.domain.mp_entity.customize.ServiceOrderEntity;
import com.ltu.enums.OrderEnums;
import com.ltu.mapper.OrderDetailMapper;
import com.ltu.mapper.OrderMapper;
import com.ltu.mapper.PayRecordMapper;
import com.ltu.redis.lock.AmountLockService;
import com.ltu.service.customize.ServiceOrderService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MqOrderServiceBize {
	
	private final OrderMapper orderMapper;
	private final PayRecordMapper payRecordMapper;
	private final OrderDetailMapper orderDetailMapper;
	private final ServiceOrderService serviceOrderService;
	@Qualifier("productStoceLock")
	@Autowired
	private  AmountLockService amountLockService;
	
	
	
	
	// 根据订单来源处理后续业务;  未支付订单，回滚数量，删除
//	@Async("customServiceExecutor")
	@Transactional(rollbackFor = Exception.class)
	public void rollBackOrder(String msg) {
		OrderEntity  o =	orderMapper.selectById(msg);
		if(Assert.isEmpty(o))
			return;
		if(!Objects.equals(o.getPayStatus(), (byte)1)) {
			o.setPayStatus((byte) -1 );
			o.setStatus(-1);
			orderMapper.updateById(o);
			QueryWrapper<PayRecord> wrapper = new QueryWrapper<PayRecord>();
			wrapper.orderByDesc("id");
			wrapper.lambda().eq(PayRecord :: getOrderId, o.getId())
			.last("limit 1 ");
			PayRecord p  =	payRecordMapper.selectOne(wrapper);
			p.setStatus((byte) -1);
			payRecordMapper.updateById(p);
			
			if(o.getSourceDict().equals(OrderEnums.OrderSource.PlaceOrder.getIndex())) {
				ServiceOrderEntity  so = this.serviceOrderService.getById(o.getSourceIds());
				so.setPayStatus(o.getPayStatus().intValue());
				this.serviceOrderService.updateById(so);
				
			}
			log.info("订单ID：{},未支付",msg);
		}else{
//			QueryWrapper<PayRecord> qw = new QueryWrapper<PayRecord>();
//			qw.lambda().eq(PayRecord :: getOrderId, msg)
//						.eq(PayRecord :: getStatus, 1)
//						.eq(PayRecord :: getUserId, o.getUserId());
//			PayRecord p =	this.payRecordMapper.selectOne(qw);
//			if(p == null)
//				return;
//			CompanyEntity c =	 this.companyService.getMeById(o.getCompanyId());
//			try {
//				wxMaLiveRestService.sendOrder(p, c);
//			} catch (WxErrorException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
		}
	}
	
}
